/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.user.api.controller;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.UserExtension;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.PayManagerService;
import com.yami.shop.service.UserExtensionService;
import com.yami.shop.user.comment.model.UserLevel;
import com.yami.shop.user.comment.model.UserLevelLog;
import com.yami.shop.user.comment.param.PayUserParam;
import com.yami.shop.user.comment.service.UserLevelLogService;
import com.yami.shop.user.comment.service.UserLevelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

/**
 * @author LHD on 2020/03/02.
 */
@Api(tags = "会员购买接口")
@RestController
@RequestMapping("/p/level")
@AllArgsConstructor
public class PayLevelController {

    /**
     * 会员信息
     */
    private final UserLevelService userLevelService;
    private final UserExtensionService userExtensionService;
//    private final ApplicationContext applicationContext;
    private final Snowflake snowflake;
    private final UserLevelLogService userLevelLogService;
    private final PayManagerService payManagerService;

    /**
     * 会员支付接口
     */
    @PostMapping("/payLevel")
    @ApiOperation(value = "根据会员等级进行支付", notes = "根据会员等级进行支付")
    @SneakyThrows
    public ResponseEntity<?> payVip(HttpServletResponse httpResponse, @RequestBody PayUserParam payCardParam) {
        YamiUser user = SecurityUtils.getUser();
        if (!user.isEnabled()) {
            // 您已被禁用，不能购买，请联系平台客服
            throw new YamiShopBindException("yami.order.pay.user.disable");
        }

        String openId = user.getBizUserId();
        UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>()
                                            .eq(UserExtension::getUserId, user.getUserId()));
        UserLevel userLevel = userLevelService.getById(payCardParam.getId());

        //如果会员等级为空
        if(userLevel == null || !Objects.equals(userLevel.getLevelType(),1)) {
            // 会员等级不存在或当前等级不为付费会员等级！
            throw new YamiShopBindException("yami.user.level.no.exist");
        }

        if(Objects.equals(userExtension.getLevelType(),1) && userExtension.getLevel() > userLevel.getLevel()){
            // 用户无法在会员期间购买低等级会员
            throw new YamiShopBindException("yami.user.pay.level.check");
        }

        if(userExtension.getGrowth() < userLevel.getNeedGrowth()){
            // 用户成长值不足，无法购买
            throw new YamiShopBindException("yami.user.growh.no.enough");
        }




        // 使用雪花算法生成支付单号
        String payNo = String.valueOf(snowflake.nextId());
        Date now = new Date();
        //生成等级日志
        UserLevelLog userLevelLog = new UserLevelLog();
        userLevelLog.setGiftTime(now);
        userLevelLog.setCreateTime(now);
        userLevelLog.setLevel(userLevel.getLevel());
        userLevelLog.setState(0);
        userLevelLog.setPayNo(payNo);
        userLevelLog.setIsPayed(0);
        userLevelLog.setUserId(userExtension.getUserId());
        //插入一条等级日志
        userLevelLogService.save(userLevelLog);

        PayInfoDto payInfo = new PayInfoDto();
        payInfo.setBody("会员等级购买");
        payInfo.setPayAmount(userLevel.getNeedAmount());
        payInfo.setPayNo(payNo);
        payInfo.setBizUserId(openId);
        payInfo.setPayType(payCardParam.getPayType());
        payInfo.setApiNoticeUrl("/notice/levelPay/levelPayCallback/" + payCardParam.getPayType());
        payInfo.setReturnUrl(payCardParam.getReturnUrl());
        //余额支付
        if (payCardParam.getPayType().equals(PayType.BALANCE.value())){
            payInfo.setUserId(user.getUserId());
            payInfo.setType(2);
        }


        return payManagerService.doPay(httpResponse, payInfo);

//       //TODO 支付成功测试
//        userLevelService.paySuccess(payNo);
//        return ResponseEntity.ok().build();
    }

    @GetMapping("/isPay")
    public ResponseEntity<Integer> isPay(){
        YamiUser user = SecurityUtils.getUser();
        UserLevelLog uLog = userLevelLogService.getMaxCrtTimeByUserId(user.getUserId());
        return ResponseEntity.ok(uLog.getIsPayed());
    }
}
